﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Web;

namespace IssueIT.WebUI.Infrastructure.Helpers
{

    public class ElementReader
    {
        public enum ErrorBehavior
        {
            Ignore,
            Raise
        }

        #region privateHelpers
        public static bool KeyExist(NameValueCollection collection, string key, ErrorBehavior errorBehavior)
        {
            if (collection == null && errorBehavior == ErrorBehavior.Raise)
            {
                throw new Exception("Collection is null");
            }

            bool result = true;
            if (collection[key] == null)
            {
                if (errorBehavior == ErrorBehavior.Raise)
                {
                    throw new Exception(string.Concat("Key is missing: ", key));
                }
                result = false;
            }

            return result;
        }

        #endregion
        public static T GetElement<T>(NameValueCollection collection, string key)
        {
            return GetElement(collection, key, default(T), ErrorBehavior.Raise);
        }

        public static T GetElement<T>(NameValueCollection collection, string key, T valueIfMissing)
        {
            return GetElement(collection, key, valueIfMissing, ErrorBehavior.Ignore);
        }

        private static T GetElement<T>(NameValueCollection collection, string key, T valueIfMissing, ErrorBehavior errorBehavior)
        {
            T result = valueIfMissing;
            if (KeyExist(collection, key, errorBehavior))
            {
                bool success = true;
                try
                {
                    result = ConvertStringTo<T>(collection[key]);
                }
                catch (Exception)
                {
                    success = false;
                }

                if (!success && errorBehavior == ErrorBehavior.Raise)
                {
                    throw new Exception(string.Format("Data is wrong format. key: {0}, value: {1}", key, collection[key]));
                }
            }

            return result;
        }

        private static T ConvertStringTo<T>(string input)
        {
            return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(input);
        }
    }
}